package kook.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import kook.domain.view.ResultView;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
@ResponseBody
@RequestMapping("/api")
public class OpenApiController {
    private OkHttpClient okhttp = new OkHttpClient();
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${protocol.token}")
    private String token;
    @Value("${default-channel}")
    private String defaultChannel;
    private String baseUrl = "https://www.kookapp.cn";

    @RequestMapping("/sendTextToChannel")
    public Object event(@org.springframework.web.bind.annotation.RequestBody JsonNode jsonNode) throws IOException {
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("type", 1);
        objectNode.put("target_id", jsonNode.path("target_id").asText(defaultChannel));
        objectNode.put("content", jsonNode.get("content").asText());

        this.post("/api/v3/message/create", objectNode);
        return ResultView.success();
    }

    @RequestMapping("/sendTextToChannel")
    public Object sendImageToChannel(@org.springframework.web.bind.annotation.RequestBody JsonNode jsonNode) {
        String file = jsonNode.get("file").asText();
        if (file.startsWith("http")) {
            if (!file.startsWith("https://img.")) {
                // 不是平台图片先上传
                file = uploadFile(file);
            }
            ObjectNode objectNode = objectMapper.createObjectNode();
            objectNode.put("type", 2);
            objectNode.put("target_id", jsonNode.path("target_id").asText(defaultChannel));
            objectNode.put("content", file);

            this.post("/api/v3/message/create", objectNode);
        }
        return ResultView.success();
    }

    public String uploadFile(String url) {
        byte[] image;
        try (Response execute = okhttp.newCall(new Request.Builder()
                .url(url)
                .get()
                .build()).execute()) {
            image = execute.body().bytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "filename.jpg", RequestBody.create(image))
                .build();
        try (Response execute = okhttp.newCall(new Request.Builder()
                .url(baseUrl+ "/asset/create")
                .post(requestBody)
                .addHeader("Content-Type", "multipart/form-data")
                .addHeader("Authorization", "Bot " + token)
                .build()).execute()) {
            JsonNode jsonNode = objectMapper.readTree(execute.body().string());
            return jsonNode.get("data").get("url").asText();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private JsonNode post(String uri, JsonNode data) {
        Request request = new Request.Builder()
                .post(RequestBody.create(MediaType.parse("application/json"), data.toString()))
                .url(baseUrl + uri)
                .addHeader("Authorization", "Bot " + token)
                .build();
        try (Response execute = okhttp.newCall(request).execute()) {
            return objectMapper.readTree(execute.body().string());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
